package com.tensquare.article.service;

import com.tensquare.article.dao.ArticleDao;
import com.tensquare.article.pojo.Article;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import javax.transaction.Transactional;
import java.util.concurrent.TimeUnit;

/**
 * Created by WF on 2020/12/15 16:21
 */
@Service
@Transactional
public class ArticleService {
    @Autowired
    private ArticleDao articleDao;
    @Autowired
    private RedisTemplate redisTemplate;

    //1.文章审核
    public void examine(String articleId) {
        articleDao.examine(articleId);
    }

    //2.文章点赞
    public void thumbup(String articleId) {
        articleDao.thumbup(articleId);
    }

    //3.根据id查询文章
    public Article findById(String articleId){
        //3.1)根据id从redis中查询文章
        Article article = (Article) redisTemplate.opsForValue().get("article_" + articleId);
        //3.2)如果找不到就从数据库中
        if(article == null){
            article = articleDao.findById(articleId).get();
            System.out.println("从数据库中查询文章。。。");
            //3.3）将文章放到redis中
            //参数1：key 参数2：值
            //参数3：代表到期时间 参数4：代表时间单位
            redisTemplate.opsForValue().set("article_"+articleId,article,10, TimeUnit.HOURS);
        }
        return article;
    }

    //4.添加文章
    public void add(Article article){
        //4.1)添加前清空redis中的文章
        redisTemplate.delete("article_"+article.getId());
        //4.2)保存
        articleDao.save(article);
    }

    //5.修改文章
    public void update(Article article){
        //4.1)添加前清空redis中的文章
        redisTemplate.delete("article_"+article.getId());
        //4.2)保存
        articleDao.save(article);
    }

}
